package think.in.java.concurrency.practise.exec6;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * Created by IntelliJ IDEA.
 * User: Richard
 * Date: 5/19/11
 * Time: 8:26 PM
 * To change this template use File | Settings | File Templates.
 */
public class EvenChecker implements Runnable {
    private int count = 0;
    private IntGenerate generate;
    private int tryTimes = 0;

    public EvenChecker(IntGenerate generate) {
        this(generate, 10);
    }

    public EvenChecker(IntGenerate generate, int count) {
        this.count = count;
        this.generate = generate;
    }

    public static void test(IntGenerate generate) {
        ExecutorService executorService = Executors.newCachedThreadPool();
        try {

            for (int i = 0; i < 10; i++) {
                executorService.execute(new EvenChecker(generate));

            }
            executorService.shutdown();
            executorService.awaitTermination(10, TimeUnit.SECONDS);
       } catch (InterruptedException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }

    }

    public void run() {
        while (!generate.getCancel()) {
            int val = generate.next();
            if (val % 2 != 0) {
                System.out.println(val + " not a even");
                generate.cancel();
            }
            Thread.yield();
            tryTimes++;
            if (tryTimes > 10000) {
                generate.cancel();
                System.out.println("after try " + tryTimes + " times , it always even !");
            }
        }
    }
}
